<template>
    <div class="task-publish-container" style="margin-bottom: 50px; padding-bottom: 10px;">
        <van-nav-bar title="发布任务" left-text="" left-arrow fixed @click-left="onClickLeft">
            <template #left>
                <van-icon name="arrow-left" size="24" color="gray" />
            </template>
        </van-nav-bar>

        <div class="content">
            <van-form @submit="onSubmit">
                <!-- 基本信息 -->
                <div class="form-card">
                    <h2 class="section-title">基本信息</h2>

                    <van-field v-model="taskForm.taskTitle" name="taskTitle" label="任务标题" placeholder="请输入任务标题（5-30字）"
                        :rules="[{ required: true, message: '请输入任务标题' }]" />

                    <van-field v-model="taskForm.taskCategoryName" is-link readonly name="taskCategoryId" label="任务类别"
                        placeholder="请选择任务类别" @click="showCategoryPicker = true"
                        :rules="[{ required: true, message: '请选择任务类别' }]" />
                    <van-popup v-model:show="showCategoryPicker" position="bottom">
                        <van-picker :columns="categoryColumns" @confirm="onCategoryConfirm"
                            @cancel="showCategoryPicker = false" />
                    </van-popup>

                    <van-field v-model="taskForm.requiredPeople" type="digit" name="requiredPeople" label="招聘人数"
                        placeholder="请输入招聘人数" :rules="[{ required: true, message: '请输入招聘人数' }]" />

                    <van-field v-model="taskForm.salary" type="digit" name="salary" label="薪资待遇" placeholder="请输入薪资金额"
                        :rules="[{ required: true, message: '请输入薪资金额' }]">
                        <template #button>
                            <van-field v-model="taskForm.salaryType" is-link readonly name="salaryType"
                                placeholder="薪资单位" @click="showSalaryTypePicker = true"
                                style="width: 100px; padding: 0;" :rules="[{ required: true, message: '请选择薪资单位' }]" />
                        </template>
                    </van-field>
                    <van-popup v-model:show="showSalaryTypePicker" position="bottom">
                        <van-picker :columns="salaryTypeColumns" @confirm="onSalaryTypeConfirm"
                            @cancel="showSalaryTypePicker = false" />
                    </van-popup>
                </div>

                <!-- 工作详情 -->
                <div class="form-card">
                    <h2 class="section-title">工作详情</h2>

                    <van-field v-model="taskForm.startTime" readonly clickable name="startTime" label="开始日期"
                        :value="taskForm.startTime" placeholder="请选择开始日期" @click="showStartDatePicker = true"
                        :rules="[{ required: true, message: '请选择开始日期' }]" />
                    <van-calendar v-model:show="showStartDatePicker" @confirm="onStartDateConfirm" />

                    <van-field v-model="taskForm.endTime" readonly clickable name="endTime" label="结束日期"
                        :value="taskForm.endTime" placeholder="请选择结束日期" @click="showEndDatePicker = true"
                        :rules="[{ required: true, message: '请选择结束日期' }]" />
                    <van-calendar v-model:show="showEndDatePicker" @confirm="onEndDateConfirm" />

                    <van-field v-model="taskForm.workHours" type="digit" name="workHours" label="工作时长"
                        placeholder="请输入每天工作时长(小时)" :rules="[{ required: true, message: '请输入工作时长' }]" />

                    <van-field v-model="taskForm.addressDetail" name="addressDetail" label="详细地址" placeholder="请输入详细地址"
                        :rules="[{ required: true, message: '请输入详细地址' }]" />

                    <van-field v-model="taskForm.taskDescription" rows="4" autosize label="工作内容" type="textarea"
                        maxlength="500" placeholder="请详细描述工作内容、职责要求等信息" show-word-limit
                        :rules="[{ required: true, message: '请输入工作内容' }]" />

                    <div class="skill-section">
                        <div class="skill-title">技能要求</div>
                        <div class="skill-tags">
                            <div v-for="(skill, index) in skillOptions" :key="index"
                                :class="['skill-tag', { active: selectedSkills.includes(skill) }]"
                                @click="toggleSkill(skill)">
                                {{ skill }}
                            </div>
                        </div>
                    </div>
                </div>

                <div class="agreement-section">
                    <van-checkbox v-model="taskForm.agreement" shape="square" icon-size="16px">
                        我已阅读并同意<span class="agreement-link">《用户服务协议》</span>和<span class="agreement-link">《隐私政策》</span>
                    </van-checkbox>
                </div>

                <div class="submit-section">
                    <van-button round block type="primary" native-type="submit" :disabled="!taskForm.agreement">
                        发布任务
                    </van-button>
                </div>
            </van-form>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import network from '../network'

const router = useRouter()

// 返回上一页
const onClickLeft = () => {
    router.back()
}

// 表单数据
const taskForm = reactive({
    taskTitle: '',
    taskCategoryId: '',
    taskCategoryName: '', // 新增字段用于显示
    jobType: '',
    requiredPeople: '',
    salary: '',
    salaryType: '',
    settlementType: '',
    startTime: '',
    endTime: '',
    workHours: '',
    province: '',
    city: '',
    district: '',
    addressDetail: '',
    taskAddress: '',
    taskDescription: '',
    contactName: '',
    contactPhone: '',
    contactWechat: '',
    agreement: false
})

// 经纬度（可通过地图API获取）
const longitude = ref(0)
const latitude = ref(0)

// 选择器状态
const showCategoryPicker = ref(false)
const showSalaryTypePicker = ref(false)
const showStartDatePicker = ref(false)
const showEndDatePicker = ref(false)

// 选择器数据
const categoryColumns = [
    { text: '电工', value: 1 },
    { text: '水工', value: 2 },
    { text: '木工', value: 3 },
    { text: '搬运', value: 4 },
    { text: '保洁', value: 5 },
    { text: '护理', value: 6 },
]


const salaryTypeColumns = [
    { text: '元/小时', value: 1 },
    { text: '元/天', value: 2 },
]

// 选择器确认回调
const onCategoryConfirm = (value: any) => {
    taskForm.taskCategoryId = value.selectedOptions[0].value
    taskForm.taskCategoryName = value.selectedOptions[0].text
    showCategoryPicker.value = false
}

const onSalaryTypeConfirm = (value: any) => {
    taskForm.salaryType = value.selectedOptions[0].text
    showSalaryTypePicker.value = false
}

const onStartDateConfirm = (date: Date) => {
    taskForm.startTime = formatDate(date)
    showStartDatePicker.value = false
}

const onEndDateConfirm = (date: Date) => {
    taskForm.endTime = formatDate(date)
    showEndDatePicker.value = false
}

// 格式化日期
const formatDate = (date: Date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
}

// 技能要求和福利待遇
const skillOptions = [
    '无需经验', '有责任心', '形象气质佳', '会开车',
    '会做饭', '会照顾老人', '会使用智能手机', '有相关经验'
]
const selectedSkills = ref<string[]>([])


const toggleSkill = (skill: string) => {
    const index = selectedSkills.value.indexOf(skill)
    if (index === -1) {
        selectedSkills.value.push(skill)
    } else {
        selectedSkills.value.splice(index, 1)
    }
}


// 提交表单
const onSubmit = () => {
    if (!taskForm.agreement) {
        showToast('请先同意用户协议')
        return
    }

    // 组装完整地址
    taskForm.taskAddress = `${taskForm.addressDetail}`

    // 组装技能要求
    const skillRequirements = selectedSkills.value.join(',')

    // 准备提交的数据
    const taskData = {
        taskTitle: taskForm.taskTitle,
        taskDescription: taskForm.taskDescription,
        taskCategoryId: taskForm.taskCategoryId,
        taskAddress: taskForm.taskAddress,
        startTime: taskForm.startTime,
        endTime: taskForm.endTime,
        workHours: parseFloat(taskForm.workHours),
        salary: parseFloat(taskForm.salary),
        salaryType: taskForm.salaryType,
        requiredPeople: parseInt(taskForm.requiredPeople),
        hiredPeople: 0,
        skillRequirements: skillRequirements,
        taskStatus: 1, // 默认为发布状态
        viewCount: 0,
        applyCount: 0,
    }

    // 调用API发布任务
    network.publishTask(taskData)
        .then((res: any) => {
            if (res.code === 100) {
                showToast('发布成功')
                router.back()
            } else {
                showToast(res.message || '发布失败')
            }
        })
        .catch((err: any) => {
            showToast('发布失败，请稍后重试')
            console.error('发布任务失败:', err)
        })
}


// 辅助函数：获取分类ID
const getCategoryId = (categoryName: string) => {
    const category = categoryColumns.find(item => item.text === categoryName)
    return category ? category.value : 1
}

// 辅助函数：获取薪资类型ID
const getSalaryTypeId = (salaryTypeName: string) => {
    const salaryType = salaryTypeColumns.find(item => item.text === salaryTypeName)
    return salaryType ? salaryType.value : 1
}
</script>

<style scoped>
.task-publish-container {
    min-height: 100vh;
    background: linear-gradient(145deg, #f8fafc, #f1f5f9);
    padding-bottom: 50px;
}

.content {
    padding-top: 46px;
    padding-bottom: 20px;
}

.form-card {
    background: #ffffff;
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
    margin: 20px;
    padding: 20px;
}

.section-title {
    font-size: 18px;
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 20px;
    position: relative;
    padding-left: 12px;
}

.section-title::before {
    content: '';
    position: absolute;
    left: 0;
    top: 4px;
    height: 16px;
    width: 4px;
    background: linear-gradient(to bottom, #4f46e5, #6366f1);
    border-radius: 2px;
}

:deep(.van-field__label) {
    width: 90px;
    color: #475569;
}

:deep(.van-field__control) {
    color: #1e293b;
}

.skill-section {
    margin-top: 20px;
    margin-bottom: 20px;
}

.skill-title {
    font-size: 14px;
    color: #475569;
    margin-bottom: 12px;
}

.skill-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.skill-tag {
    display: inline-flex;
    align-items: center;
    padding: 8px 16px;
    border-radius: 8px;
    border: 1px solid #e2e8f0;
    color: #64748b;
    font-size: 14px;
    transition: all 0.2s;
    cursor: pointer;
}

.skill-tag.active {
    background-color: #4f46e5;
    color: white;
    border-color: #4f46e5;
}

.upload-section {
    margin-top: 20px;
}

.upload-title {
    font-size: 14px;
    color: #475569;
    margin-bottom: 12px;
}

.upload-tips {
    font-size: 12px;
    color: #94a3b8;
    margin-top: 8px;
}

.agreement-section {
    margin: 20px;
    display: flex;
    align-items: center;
}

.agreement-link {
    color: #4f46e5;
}

.submit-section {
    margin: 20px;
}

:deep(.van-button--primary) {
    background: linear-gradient(to right, #4f46e5, #6366f1);
    border: none;
    font-size: 16px;
    font-weight: 500;
    height: 44px;
    box-shadow: 0 4px 12px rgba(79, 70, 229, 0.2);
}

:deep(.van-nav-bar) {
    background-color: #fff;
}

:deep(.van-nav-bar__title) {
    font-size: 18px;
    font-weight: bold;
    color: #333;
}
</style>